import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.*;
import java.io.File;

/**
 * TODO
 *
 * @author TANGYE
 * @2021/1/14 17:54
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "xmlTest")
public class XmlTest {

    private int id;
    @XmlElement(required = true, name = "name")
    @XmlAnyElement
    private String name;

    public XmlTest() {

    }

    public XmlTest(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public static void main(String[] args) {
        XmlTest person = new XmlTest(1, null);
        File file = new File("D://XmlTest.xml");
        JAXBContext jc = null;
        try {
            //根据person类生成上下文对象
            jc = JAXBContext.newInstance(XmlTest.class);
            //从上下文中获取Marshaller对象，用作将bean编组(转化)为xml
            Marshaller marshaller = jc.createMarshaller();
            //以下是为生成xml做的一些配置
            //格式化输出，即按标签自动换行，否则就是一行输出
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            //设置编码(默认编码就是utf-8)
            marshaller.setProperty(Marshaller.JAXB_ENCODING, "utf-8");
            //是否省略xml头信息，默认不省略(false)
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false);
            //编组
            marshaller.marshal(person, file);
            System.out.println("对象转换成xml文件成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
